import axios from 'axios';
import { getToken, removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'

let instance = axios.create({
  timeout: 1000 * 60 * 40,
});

//请求拦截
instance.interceptors.request.use(config => {
  const isToken = (config.headers || {}).isToken === false;
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken()
  }
  return config
}, error => {

})

//响应拦截
instance.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200;
  // 获取错误信息
  const msg = errorCode[code] || res.data.msg || errorCode['default']
  // 二进制数据则直接返回
  if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
    return res.data
  }
  if (code === 401) {
    removeToken();
    window.location.href = '/homePage'
    return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
  } else if (code === 500) {
    return Promise.reject(new Error(msg))
  } else if (code === 601) {
    return Promise.reject(new Error(msg))
  } else if (code !== 200) {
    return Promise.reject('error')
  } else {
    return  Promise.resolve(res.data)
  }
}, error => {

})

export default instance;
